package com.vincent.filepicker.adapter;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.vincent.filepicker.Constant;
import com.vincent.filepicker.ResourceTable;
import com.vincent.filepicker.ToastUtil;
import com.vincent.filepicker.ability.ImageBrowserAbility;
import com.vincent.filepicker.ability.ImagePickAbility;
import com.vincent.filepicker.camera.CameraAbility;
import com.vincent.filepicker.filter.entity.ImageFile;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.app.Context;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.util.ArrayList;

import static com.vincent.filepicker.ability.ImageBrowserAbility.IMAGE_BROWSER_INIT_INDEX;
import static com.vincent.filepicker.ability.ImageBrowserAbility.IMAGE_BROWSER_SELECTED_LIST;

/**
 * Created by Vincent Woo
 * Date: 2016/10/13
 * Time: 16:07
 */

public class ImagePickAdapter extends BaseAdapter<ImageFile> {
    private boolean isNeedImagePager;
    private boolean isNeedCamera;
    private int mMaxNumber;
    private int mCurrentNumber = 0;
    public String mImagePath;
    public Uri mImageUri;
    private Context mContext;
    private final int mItemMargin = 6;
    private final int mItemMarginWidth = 15;

    public ImagePickAdapter(Context ctx, boolean needCamera, boolean isNeedImagePager, int max) {
        this(ctx, new ArrayList<ImageFile>(), needCamera, isNeedImagePager, max);
    }

    public ImagePickAdapter(Context ctx, ArrayList<ImageFile> list, boolean needCamera, boolean needImagePager, int max) {
        super(ctx, list);
        mContext = ctx;
        isNeedCamera = needCamera;
        mMaxNumber = max;
        isNeedImagePager = needImagePager;
    }

    @Override
    public int getCount() {
        return isNeedCamera ? mList.size() + 1 : mList.size();
    }

    @Override
    public Object getItem(int i) {
        return mList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }


    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {

        ImagePickViewHolder viewHolder = null;
        if (component == null) {
            viewHolder = new ImagePickViewHolder();
            component = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_vw_layout_item_image_pick, null, false);
            viewHolder.mIvCamera = (Image) component.findComponentById(ResourceTable.Id_iv_camera);
            viewHolder.mIvThumbnail = (Image) component.findComponentById(ResourceTable.Id_iv_thumbnail);
            viewHolder.mShadow = component.findComponentById(ResourceTable.Id_shadow);
            viewHolder.mCbx = (Checkbox) component.findComponentById(ResourceTable.Id_cbx);
            component.setTag(viewHolder);
        } else {
            viewHolder = (ImagePickViewHolder) component.getTag();
        }
        ComponentContainer.LayoutConfig params = component.getLayoutConfig();
        if (params != null) {
            int width = mContext.getResourceManager().getDeviceCapability().width
                    * mContext.getResourceManager().getDeviceCapability().screenDensity / 160;
            ComponentContainer.LayoutConfig layoutConfig = component.getLayoutConfig();
            layoutConfig.width = width / ImagePickAbility.COLUMN_NUMBER - mItemMarginWidth;
            layoutConfig.height = width / ImagePickAbility.COLUMN_NUMBER - mItemMarginWidth;
            layoutConfig.setMargins(mItemMargin, mItemMargin, mItemMargin, mItemMargin);
            component.setLayoutConfig(layoutConfig);
        }

        if (isNeedCamera && position == 0) {
            viewHolder.mIvCamera.setVisibility(Component.VISIBLE);
            viewHolder.mIvThumbnail.setVisibility(Component.INVISIBLE);
            viewHolder.mCbx.setVisibility(Component.INVISIBLE);
            viewHolder.mShadow.setVisibility(Component.INVISIBLE);
            component.setClickedListener(component1 -> {
                Intent cameraIntent = new Intent();
                Operation operation1 =
                        new Intent.OperationBuilder()
                                .withBundleName(mContext.getBundleName())
                                .withAbilityName(CameraAbility.class.getName())
                                .build();
                cameraIntent.setOperation(operation1);
                ((Ability) mContext).startAbilityForResult(cameraIntent, Constant.REQUEST_CODE_TAKE_IMAGE);
            });
        } else {
            viewHolder.mIvCamera.setVisibility(Component.INVISIBLE);
            viewHolder.mIvThumbnail.setVisibility(Component.VISIBLE);
            viewHolder.mCbx.setVisibility(Component.VISIBLE);

            ImageFile file;
            if (isNeedCamera) {
                file = mList.get(position - 1);
            } else {
                file = mList.get(position);
            }

            Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, String.valueOf(file.getId()));
            Glide.with(mContext)
                    .load(uri)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .skipMemoryCache(true)
                    .into(viewHolder.mIvThumbnail);

            if (file.isSelected()) {
                viewHolder.mCbx.setChecked(true);
                viewHolder.mShadow.setVisibility(Component.VISIBLE);
            } else {
                viewHolder.mCbx.setChecked(false);
                viewHolder.mShadow.setVisibility(Component.INVISIBLE);
            }

            ImagePickViewHolder finalViewHolder = viewHolder;
            viewHolder.mCbx.setCheckedStateChangedListener((absButton, b) -> {
                if (!b && isUpToMax()) {
                    ToastUtil.getInstance(mContext).showToast(ResourceTable.String_vw_up_to_max);
                    return;
                }

                int index = isNeedCamera ? position - 1 : position;
                if (b) {
                    finalViewHolder.mShadow.setVisibility(Component.VISIBLE);
                    finalViewHolder.mCbx.setChecked(true);
                    mCurrentNumber++;
                    mList.get(index).setSelected(true);
                } else {
                    finalViewHolder.mShadow.setVisibility(Component.INVISIBLE);
                    finalViewHolder.mCbx.setChecked(false);
                    mCurrentNumber--;
                    mList.get(index).setSelected(false);
                }

                if (mListener != null) {
                    mListener.OnSelectStateChanged(finalViewHolder.mCbx.isChecked(), mList.get(index));
                }
            });

            if (isNeedImagePager) {
                component.setClickedListener(component1 -> {
                    Intent intent1 = new Intent();
                    Operation operation1 =
                            new Intent.OperationBuilder()
                                    .withBundleName(mContext.getBundleName())
                                    .withAbilityName(ImageBrowserAbility.class.getName())
                                    .build();
                    intent1.setParam(Constant.MAX_NUMBER, mMaxNumber);
                    intent1.setParam(IMAGE_BROWSER_INIT_INDEX, isNeedCamera ? position - 1 : position);
                    intent1.setSequenceableArrayListParam(IMAGE_BROWSER_SELECTED_LIST, ((ImagePickAbility) mContext).mSelectedList);
                    intent1.setOperation(operation1);
                    ((Ability) mContext).startAbilityForResult(intent1, Constant.REQUEST_CODE_BROWSER_IMAGE);

                });
            } else {
                ImagePickViewHolder finalViewHolder1 = viewHolder;
                viewHolder.mIvThumbnail.setClickedListener(component1 -> {
                    if (!finalViewHolder1.mCbx.isSelected() && isUpToMax()) {
                        ToastUtil.getInstance(mContext).showToast(ResourceTable.String_vw_up_to_max);
                        return;
                    }

                    int index = isNeedCamera ? position - 1 : position;
                    if (finalViewHolder1.mCbx.isSelected()) {
                        finalViewHolder1.mShadow.setVisibility(Component.INVISIBLE);
                        finalViewHolder1.mCbx.setChecked(false);
                        mCurrentNumber--;
                        mList.get(index).setSelected(false);
                    } else {
                        finalViewHolder1.mShadow.setVisibility(Component.VISIBLE);
                        finalViewHolder1.mCbx.setChecked(true);
                        mCurrentNumber++;
                        mList.get(index).setSelected(true);
                    }

                    if (mListener != null) {
                        mListener.OnSelectStateChanged(finalViewHolder1.mCbx.isSelected(), mList.get(index));
                    }
                });
            }
        }

        return component;
    }

    class ImagePickViewHolder {
        private Image mIvCamera;
        private Image mIvThumbnail;
        private Component mShadow;
        private Checkbox mCbx;
    }

    public boolean isUpToMax() {
        return mCurrentNumber >= mMaxNumber;
    }

    public void setCurrentNumber(int number) {
        mCurrentNumber = number;
    }
}
